package product

import (
	"errors"
	config "pd/server/app/pd/config"
	form "pd/server/app/pd/form/product"
	logic "pd/server/app/pd/logic/product"
	userLogic "pd/server/app/pd/logic/user"
	model "pd/server/app/pd/model/product"
	"pd/server/plugin/api"
	"pd/server/plugin/auth"
	"pd/server/plugin/logger"

	"github.com/gin-gonic/gin"
)

var productLogic logic.ProductLogic

// 新增商品
func Create(router *gin.RouterGroup, conf *config.Config) {
	router.POST("/add", func(c *gin.Context) {
		var frm = new(model.ProductModel)
		var err error
		if err = api.Bind(c, &frm); err != nil {
			return
		}
		if frm.Name == "" {
			api.No(c, errors.New("商品名称不能为空"))
			return
		}
		authInfo := auth.GetAuthInfo(c)
		if frm.MerchantId, err = userLogic.GetUserMerchantId(c, authInfo.UserId); err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		err = productLogic.Create(c, frm)
		if err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		api.Ok(c, frm)
	})
}

// 编辑商品
func Update(router *gin.RouterGroup, conf *config.Config) {
	router.POST("/edit", func(c *gin.Context) {
		var frm = new(model.ProductModel)
		var err error
		if err = api.Bind(c, &frm); err != nil {
			return
		}
		if frm.Id == 0 {
			api.No(c, errors.New("商品ID不能为空"))
			return
		}
		authInfo := auth.GetAuthInfo(c)
		if frm.MerchantId, err = userLogic.GetUserMerchantId(c, authInfo.UserId); err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		err = productLogic.Update(c, frm)
		if err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		api.Ok(c, frm)
	})
}

// 删除商品
func Delete(router *gin.RouterGroup, conf *config.Config) {
	router.POST("/remove", func(c *gin.Context) {
		var frm = new(model.ProductModel)
		var err error
		if err = api.Bind(c, &frm); err != nil {
			return
		}
		if frm.Id == 0 {
			api.No(c, errors.New("商品ID不能为空"))
			return
		}
		authInfo := auth.GetAuthInfo(c)
		if frm.MerchantId, err = userLogic.GetUserMerchantId(c, authInfo.UserId); err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		err = productLogic.Delete(c, frm)
		if err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		api.Ok(c, frm.Id)
	})
}

// 商品列表
func List(router *gin.RouterGroup, conf *config.Config) {
	router.POST("/page", func(c *gin.Context) {
		var frm = new(form.ListForm)
		var err error
		if err = api.Bind(c, &frm); err != nil {
			return
		}
		authInfo := auth.GetAuthInfo(c)
		if frm.MerchantId, err = userLogic.GetUserMerchantId(c, authInfo.UserId); err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		productList, total, err := productLogic.List(c, frm)
		if err != nil {
			logger.Error(err)
			api.No(c, err)
			return
		}

		api.Ok(c, gin.H{
			"total":   total,
			"current": frm.Current,
			"size":    frm.Size,
			"records": productList,
		})
	})
}
